<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
      size="mini"
    >
      <el-form-item label="分类" prop="categoryId">
        <el-cascader
          v-model="categoryName"
          :options="options"
          @change="handleChange"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <el-select v-model="dataForm.courseId" placeholder="请选择课程">
          <el-option
            v-for="item in courses"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="dataForm.type" placeholder="请选择类型">
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="问题" prop="question">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 10 }"
          placeholder="请输入问题"
          v-model="dataForm.question"
        >
        </el-input>
      </el-form-item> -->
      <el-form-item label="题目" prop="question">
        <ueditor v-model="dataForm.question"></ueditor>
      </el-form-item>
      <el-form-item label="答案" prop="answer">
        <ueditor v-model="dataForm.answer"></ueditor>
      </el-form-item>
      <!-- <el-form-item label="答案" prop="answer">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 10 }"
          placeholder="请输入答案"
          v-model="dataForm.answer"
        >
        </el-input>
      </el-form-item> -->
      <el-form-item label="分数" prop="score">
        <el-input
          v-model.number="dataForm.score"
          placeholder="分数"
          type="number"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="录入人" prop="input">
      <el-input v-model="dataForm.input" placeholder="录入人"></el-input>
    </el-form-item> -->
      <!-- <el-form-item label="创建时间" prop="createTime">
      <el-input v-model="dataForm.createTime" placeholder="创建时间"></el-input>
    </el-form-item>
    <el-form-item label="修改时间" prop="updateTime">
      <el-input v-model="dataForm.updateTime" placeholder="修改时间"></el-input>
    </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Ueditor from "../../common/ueditor";
export default {
  data() {
    return {
      types: [
        {
          value: "选择",
          label: "选择"
        },
        {
          value: "填空",
          label: "填空"
        },
        {
          value: "问答",
          label: "问答"
        }
      ],
      courses: [],
      categoryName: [],
      options: [],
      visible: false,
      dataForm: {
        id: 0,
        categoryId: "",
        courseId: "",
        type: "",
        question: "",
        answer: "",
        score: 0,
        input: "",
        createTime: "",
        updateTime: ""
      },
      dataRule: {
        categoryId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程不能为空", trigger: "blur" }
        ],
        type: [
          {
            required: true,
            message: "类型不能为空",
            trigger: "blur"
          }
        ],
        question: [
          { required: true, message: "问题不能为空", trigger: "blur" }
        ],
        answer: [{ required: true, message: "答案不能为空", trigger: "blur" }],
        score: [
          { required: true, message: "分数不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!Number.isInteger(value)) {
                callback(new Error("请输入数字值"));
              } else {
                if (value <= 0) {
                  callback(new Error("数字必须大于0"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  components: {
    Ueditor
  },
  methods: {
    formatCategoryPath(parent, children) {
      let d = [];
      children.forEach(item => {
        let model = {};
        model.label = item.name;
        model.value = item.id;
        if (item.children.length > 0) {
          this.formatCategoryPath(model, item.children);
        }
        d.push(model);
      });
      parent.children = d;
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.courses = [];
      (this.categoryName = []),
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          this.options = [];
          // 获取分类信息
          this.$http({
            url: this.$http.adornUrl(`/web/category/get/category/list`),
            method: "get"
          }).then(({ data }) => {
            if (data && data.code === 0) {
              let res = data.data;
              let d = [];
              res.forEach(item => {
                let model = {};
                model.label = item.name;
                model.value = item.id;
                if (item.children.length > 0) {
                  this.formatCategoryPath(model, item.children);
                }
                d.push(model);
              });
              this.options = d;
            }
          });
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/web/testquestion/info/${this.dataForm.id}`
              ),
              method: "get",
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.categoryId = data.testquestion.categoryId;
                this.dataForm.courseId = data.testquestion.courseId;
                this.dataForm.type = data.testquestion.type;
                this.dataForm.question = data.testquestion.question;
                this.dataForm.answer = data.testquestion.answer;
                this.dataForm.score = data.testquestion.score;
                // this.dataForm.input = data.testquestion.input;
                // this.dataForm.createTime = data.testquestion.createTime;
                // this.dataForm.updateTime = data.testquestion.updateTime;
                this.$http({
                  url: this.$http.adornUrl(
                    `/web/category/get/category/${
                      this.dataForm.categoryId
                    }/layer`
                  ),
                  method: "get"
                }).then(({ data }) => {
                  if (data && data.code === 0) {
                    this.categoryName = data.data.categoryIdLayer;
                  }
                });
                // 获取课程信息
                let categoryId = this.dataForm.categoryId;
                this.$http({
                  url: this.$http.adornUrl(
                    `/web/course/get/list/by/${categoryId}`
                  ),
                  method: "get"
                }).then(({ data }) => {
                  let courses = data.data;

                  courses.forEach(item => {
                    let course = {
                      value: item.id,
                      label: item.name
                    };
                    this.courses.push(course);
                  });
                });
              }
            });
          }
        });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/web/testquestion/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              categoryId: this.dataForm.categoryId,
              courseId: this.dataForm.courseId,
              type: this.dataForm.type,
              question: this.dataForm.question,
              answer: this.dataForm.answer,
              score: this.dataForm.score,
              input: this.dataForm.input,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    handleChange(value) {
      this.dataForm.categoryId = value[value.length - 1];
      this.dataForm.courseId = "";
      // 获取课程信息
      this.courses = [];
      let categoryId = this.dataForm.categoryId;
      if (categoryId != null && categoryId !== "" && categoryId !== 0) {
        this.$http({
          url: this.$http.adornUrl(`/web/course/get/list/by/${categoryId}`),
          method: "get"
        }).then(({ data }) => {
          let courses = data.data;

          courses.forEach(item => {
            let course = {
              value: item.id,
              label: item.name
            };
            this.courses.push(course);
          });
        });
      }
    }
  }
};
</script>

<style></style>
